import matplotlib.pyplot as plt
from custom import *
from PCA_tools import draw_vocab_pca
from torch import nn
from d2l import torch as d2l
import torch


def get_lstm_params(embedding_size, vocab_size, num_hiddens, device):
    num_inputs = embedding_size
    num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    def three():
        return (normal((num_inputs, num_hiddens)),
                normal((num_hiddens, num_hiddens)),
                torch.zeros(num_hiddens, device=device))

    W_xi, W_hi, b_i = three()  # 输入门参数
    W_xf, W_hf, b_f = three()  # 遗忘门参数
    W_xo, W_ho, b_o = three()  # 输出门参数
    W_xc, W_hc, b_c = three()  # 候选记忆元参数
    # 输出层参数
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)
    # 附加梯度
    params = [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc,
              b_c, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params


def init_lstm_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),
            torch.zeros((batch_size, num_hiddens), device=device))


def lstm(inputs, state, params):
    [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c,
     W_hq, b_q] = params
    (H, C) = state
    outputs = []
    for X in inputs:
        I = torch.sigmoid((X @ W_xi) + (H @ W_hi) + b_i)
        F = torch.sigmoid((X @ W_xf) + (H @ W_hf) + b_f)
        O = torch.sigmoid((X @ W_xo) + (H @ W_ho) + b_o)
        C_tilda = torch.tanh((X @ W_xc) + (H @ W_hc) + b_c)
        C = F * C + I * C_tilda
        H = O * torch.tanh(C)
        Y = (H @ W_hq) + b_q
        outputs.append(Y)
    """
    T=28    时间序列长度
    N=32    batch_size
    D=128   词嵌入长度
    V=932   词表大小
    H=256   隐变量长度
    
    X [28,32,128]
    Y [896, 932]
    H [32, 256]  
    C [32, 256]
    """
    return torch.cat(outputs, dim=0), (H, C)


# 加载之前准备好的数据
batch_size, num_steps = 32, 28
num_hiddens = 256
embedding_size = 128
train_iter, vocab = load_data_time_machine(batch_size, num_steps)

vocab_size, num_hiddens, device = len(vocab), 256, d2l.try_gpu()
num_epochs, lr = 10, 1
model = RNNModelScratch(embedding_size, len(vocab), num_hiddens, device, get_lstm_params,
                        init_lstm_state, lstm)
train_ch8(model, train_iter, vocab, lr, num_epochs, device)
print("net.embedding.weight.data 大小", model.embedding.weight.data.shape)
word = "每个"
p_words = predict(word, model, vocab, device)

# 降维度加显示
draw_vocab_pca(model.embedding.weight.data, vocab, dim=3)
plt.show()
